package concurrent.spring.concurrent;


import java.util.concurrent.*;

/**
 * 适配器 将CompletableFuture或CompletionStage适配为 ListenableFuture。
 */
public class CompletableToListenableFutureAdapter<T> implements ListenableFuture<T> {

    private final CompletableFuture<T> completableFuture;

    private final ListenableFutureCallbackRegistry<T> callback = new ListenableFutureCallbackRegistry<>();

    public CompletableToListenableFutureAdapter(CompletionStage<T> completionStage) {
        this(completionStage.toCompletableFuture());
    }

    public CompletableToListenableFutureAdapter(CompletableFuture<T> completableFuture) {
        this.completableFuture = completableFuture;
        this.completableFuture.whenComplete((result, ex) -> {
            if (ex != null) {
                callback.failure(ex);
            } else {
                callback.success(result);
            }
        });
    }

    @Override
    public void addCallback(ListenableFutureCallback<? super T> callback) {
        this.callback.addCallback(callback);

    }

    @Override
    public void addCallable(SuccessCallback<? super T> callback, FailureCallback failureCallback) {
        this.callback.addFailCallable(failureCallback);
        this.callback.addSuccessCallable(callback);

    }

    @Override
    public CompletableFuture<T> completable() {
        return this.completableFuture;
    }


    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return completableFuture.cancel(mayInterruptIfRunning);
    }

    @Override
    public boolean isCancelled() {
        return completableFuture.isCancelled();
    }

    @Override
    public boolean isDone() {
        return completableFuture.isDone();
    }

    @Override
    public T get() throws InterruptedException, ExecutionException {
        return completableFuture.get();
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return completableFuture.get(timeout, unit);
    }
}
